package cn.maxxieyi.aichatbot.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.maxxieyi.aichatbot.dto.AiChatRequest;
import cn.maxxieyi.aichatbot.dto.LinkAiChatRequest;
import cn.maxxieyi.aichatbot.dto.LinkAiChatResponse;
import cn.maxxieyi.aichatbot.service.AiApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.stream.Collectors;

@Service
public class LinkAiApiServiceImpl implements AiApiService {

    @Value("${ai.link-ai.apiUrl}")
    private String apiUrl = "https://api.link-ai.tech/v1/chat/completions";
    /**
     * 文本对话接口
     *
     * @param aiChatRequest
     * @return
     */
    @Override
    public LinkAiChatResponse chatText(AiChatRequest aiChatRequest) {
        LinkAiChatRequest linkAiChatRequest = (LinkAiChatRequest)aiChatRequest;
        String result = HttpRequest.post(apiUrl)
                .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
                .header(Header.AUTHORIZATION.getValue(), "Bearer "+linkAiChatRequest.getToken())
                .body(JSON.toJSONString(linkAiChatRequest))
//                .timeout(10000)
                .execute().body();
        LinkAiChatResponse aiChatResponse = JSON.parseObject(result, LinkAiChatResponse.class);
        if(CollUtil.isNotEmpty(aiChatResponse.getChoices())){
            aiChatResponse.setSuccess(true);
            aiChatResponse.setReplyContent(aiChatResponse.getChoices().stream().map(LinkAiChatResponse.ChoiceVO::getMessage)
                    .map(LinkAiChatResponse.ChoiceVO.MessageVO::getContent).collect(Collectors.joining()));
        }else{
            aiChatResponse.setSuccess(false);
        }

        return aiChatResponse;
    }

    /**
     * @param params
     * @return
     */
    @Override
    public LinkAiChatRequest buildChatRequest(JSONObject params) {
        LinkAiChatRequest aiChatRequest = LinkAiChatRequest.builder()
                .token(params.getString("aiApiToken"))
                .appCode(params.getString("aiApiKey"))
                .messages(Arrays.asList(LinkAiChatRequest.MessageVO.builder()
                                .role("user")
                                .content(params.getString("content"))
                        .build()))
                .build();

        return aiChatRequest;
    }
}
